package com.ucl.web.controller.system;

import com.ucl.common.util.UploadUtils;
import com.ucl.model.common.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 头像上传
 */
@Slf4j
@RestController
@RequestMapping("/api/system/avater")
public class AvatarUploadController {


    public final static String avatarPath = "avatar\\";

    @GetMapping(value = "/upload")
    public ApiResult file() {
        return ApiResult.ok("file");
    }

    @PostMapping(value = "/upload")
    public ApiResult fileUpload(@RequestParam(value = "file") MultipartFile file, Model model, HttpServletRequest request) {
        if (file.isEmpty()) {
            log.info("文件为空空");
        }
        String fileName = file.getOriginalFilename();  // 文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名


        fileName = UUID.randomUUID() + suffixName; // 新文件名
        String newPath = UploadUtils.getStaticPath() + avatarPath + fileName;
        log.info("newPath:"+newPath);
        File dest = new File(newPath);

        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }

        Map<String, Object> resultMap = new HashMap<>();
        try {
            file.transferTo(dest);
            resultMap.put("type","img_avatar");
            resultMap.put("filePath",avatarPath+fileName);
        } catch (IOException e) {
            log.error(e.getMessage(),e);
            return ApiResult.fail("IOException");
        }
        return ApiResult.ok("file",resultMap);
    }
}

